package untils

import (
	"errors"
	"gateway/basic/config"
	"github.com/gin-gonic/gin"
	"log"
	"os"
	"path/filepath"
)

func UploadImg(c *gin.Context) (string, error) {
	file, err := c.FormFile("file")
	if err != nil {
		return "", errors.New("获取文件失败" + err.Error())
	}
	log.Println(file.Filename)
	var allowExt = map[string]bool{
		".jpg":  true,
		".png":  true,
		".jpeg": true,
	}
	if !allowExt[filepath.Ext(file.Filename)] {
		return "", errors.New("格式错误，请上传jpg、png、jpeg或gif格式的文件")
	}

	dst := config.UploadPath

	err = os.MkdirAll(dst, 0755)
	if err != nil {
		return "", errors.New("创建保存目录失败" + err.Error())
	}
	tPath := filepath.Join(dst, file.Filename)

	// 上传文件至指定的完整文件路径
	if err = c.SaveUploadedFile(file, tPath); err != nil {
		return "", errors.New("保存文件失败" + err.Error())
	}

	return "http://localhost:8080/upload/" + file.Filename, nil
}
